package com.edushare.common.dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.query.SelectQuery;

import com.edushare.common.constants.ApplicationConstants;
import com.edushare.common.orm.ORMInterface;
import com.edushare.common.vo.GroupMembers;
import com.edushare.common.vo.Groups;
import com.edushare.common.vo.Users;

public class GroupsMembersDAO extends CayenneBasedDAO {

	public GroupsMembersDAO(ORMInterface ormInterface) {
		super(ormInterface);
	}

	public void addNewMember(Groups group, Users member, int role){
		addNewMember(group, member, role, GroupMembers.STATUS_INVITED);
	}

	public void addNewMember(Groups group, Users member, int role, int status) {
		GroupMembers gm = getDataContext().newObject(GroupMembers.class);
		gm.setCreationTimestamp(new Date());
		gm.setGroup(group);
		gm.setUser(member);
		gm.setRole(role);
		gm.setStatus(status);
		getDataContext().commitChanges();
	}

	public void update(GroupMembers gm) {
		getDataContext().commitChanges();
	}

	public void delete(GroupMembers gm) {
		getDataContext().deleteObject(gm);
		getDataContext().commitChanges();
	}

	public List<GroupMembers> getOutstandingInvites(Users u) {
		List<GroupMembers> gms = u.getGroupMemberships();
		ArrayList<GroupMembers> invites = new ArrayList<GroupMembers>();
		for(GroupMembers gm: gms){
			if(gm.getStatus()==GroupMembers.STATUS_INVITED){
				invites.add(gm);
			}
		}
		return invites;
	}
	
	public void remove(GroupMembers membership) {
		getDataContext().deleteObject(membership);
		getDataContext().commitChanges();
	}

	public List<Users> getMembers(Groups g, int status) {
		Expression exp = Expression.fromString("groupMemberships.group = $grp and groupMemberships.status = $stts");
		HashMap<String, Object> hm = new HashMap<String, Object>();
		hm.put("grp", g);
		hm.put("stts", status);
		SelectQuery query = new SelectQuery(Users.class, exp.expWithParameters(hm));
		query.setPageSize(ApplicationConstants.PAGE_SIZE_THREE_A_ROW);
		return getDataContext().performQuery(query);
	}
	
	public List<Users> getMembersByType(Groups g, int memberType){
		Expression exp = Expression.fromString("groupMemberships.group = $grp and groupMemberships.role = $memType groupMemberships.status = $stts");
		HashMap<String, Object> hm = new HashMap<String, Object>();
		hm.put("grp", g);
		hm.put("memType", memberType);
		hm.put("stts", GroupMembers.STATUS_ACTIVE);
		SelectQuery query = new SelectQuery(Users.class, exp.expWithParameters(hm));
		query.setPageSize(ApplicationConstants.PAGE_SIZE_THREE_A_ROW);
		return getDataContext().performQuery(query);
	}
}
